<template>
  <view>
    <block v-if="userInfo.nickName">
      <image :src="userInfo.avatarUrl" @longpress="uploadImage" alt=""></image>
      {{ userInfo.nickName }}
    </block>
    <block v-else>
      <button @click="getUserProfile">点击获取用户头像昵称</button>
    </block>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {}
    }
  },
  methods: {
    promiseUpload(tempFilePaths) {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'http://127.0.0.1:3000/api/oss/server-upload',
          filePath: tempFilePaths[0],
          name: 'img',
          success: res => {
            resolve(res)
          },
          fail: error => {
            reject(error)
          }
        })
      })
    },
    async uploadImage() {
      try {
        const chooseImageRes = await wx.chooseImage()
        const tempFilePaths = chooseImageRes.tempFilePaths
        const uploadRes = await this.promiseUpload(tempFilePaths)
        console.log('uploadRes:', uploadRes)
        const imgUrl = JSON.parse(uploadRes.data)?.data?.url
        this.userInfo.avatarUrl = imgUrl
        console.log('tempFilePaths:', imgUrl)
        wx.showToast({ title: '上传成功' })
      } catch (error) {
        wx.showToast({ title: error })
      }

      // wx.chooseImage({
      //   success: (res) => {
      //     const tempFilePaths = res.tempFilePaths
      //     console.log('tempFilePaths:', tempFilePaths)
      //     wx.uploadFile({
      //       url: 'http://127.0.0.1:3000/api/oss/upload', //仅为示例，非真实的接口地址
      //       filePath: tempFilePaths[0],
      //       name: 'img',
      //       success: (res) => {
      //         console.log('dat:,', JSON.parse(res.data).data.url)
      //         const imgUrl = JSON.parse(res.data)?.data?.url
      //         this.userInfo.avatarUrl = imgUrl
      //       },
      //     })
      //   },
      // })
    },
    getUserProfile() {
      console.log('1')
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: res => {
          console.log(res)
          this.userInfo = res.userInfo
        }
      })
    }
  }
}
</script>

<style lang="scss"></style>
